package com.meizhuang.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.meizhuang.ShoppingCartExt;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.OfferProduct;
import com.meizhuang.entity.ShoppingCart;
import com.meizhuang.entity.UserInfo;
import com.meizhuang.result.JsonResult;
import com.meizhuang.service.OfferProductService;
import com.meizhuang.service.ShopService;
import com.meizhuang.service.UserInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 加购和购物车
 */
@ApiIgnore
@RestController
public class ShopController extends BaseController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private OfferProductService offerProductService;
    /**
     * 加购
     * @param request
     * @return
     */
    @RequestMapping(value = "/shop_add")
    public JsonResult shop_add(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new HashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String productId = request.getParameter("productId");
        String num = request.getParameter("num");
        String keyWord = request.getParameter("keyWord");
        String store = request.getParameter("store"); //收藏

        if(StringUtils.isBlank(num)){
            num = "1";
        }

        OfferProduct offerProduct = offerProductService.selectById(productId);

        if(null == offerProduct) {
            retMap.put("msg", "无效产品");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<ShoppingCart> shoppingCartEntityWrapper = new EntityWrapper();
        shoppingCartEntityWrapper.eq("offset_product_id",productId);
        shoppingCartEntityWrapper.eq("uid",userSession);
        if(StringUtils.equals("1",store)){ //传1代表收藏
            shoppingCartEntityWrapper.eq("store",Integer.parseInt(store));
        }

        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            ShoppingCart shoppingCart = shopService.selectOne(shoppingCartEntityWrapper);

            if(null == shoppingCart) {
                shoppingCart = new ShoppingCart();
                shoppingCart.setNum(Integer.parseInt(num));
                shoppingCart.setOffsetProductId(Integer.parseInt(productId));
                shoppingCart.setUid(userSession);
                Date date = new Date();
                shoppingCart.setCreateTime(date);
                shoppingCart.setUpdateTime(date);
                shoppingCart.setOffsetProductUid(offerProduct.getUid());
                shoppingCart.setOfferProduct(offerProduct.getOfferProduct());
                shoppingCart.setKeyWord(keyWord);

                if(StringUtils.equals("1",store)){ //传1代表收藏
                    shoppingCart.setStore(Integer.parseInt(store));
                }
                shopService.insert(shoppingCart);
            }else{
                shoppingCart.setNum(Integer.parseInt(num));
                shoppingCart.setUpdateTime(new Date());

                if(StringUtils.equals("1",store)){ //传1代表收藏
                    shoppingCart.setStore(Integer.parseInt(store));
                }
                shopService.updateById(shoppingCart);
            }
        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.lock();
        }



        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 购物车
     * @return
     */
    @RequestMapping(value = "/shop_list")
    public JsonResult shop_list(HttpServletRequest request, HttpServletResponse response){

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        Map<String,Object> retMap = new HashMap<>();
        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String store = request.getParameter("store"); //收藏

        EntityWrapper<ShoppingCart> wrapper = new EntityWrapper();

        if(StringUtils.equals("1",store)){ //传1代表收藏
            wrapper.eq("store",Integer.parseInt(store));
        }else{
            wrapper.eq("store",0);
        }
        wrapper.eq("uid", userSession);

        List<ShoppingCart> shoppingCarts = shopService.selectList(wrapper);


        if(CollectionUtils.isEmpty(shoppingCarts)){
            retMap.put("shoppingCartList",new ArrayList<>());
            return JsonResult.buildSuccess(retMap);
        }
        //查询商家
        EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
        userInfoWrapper.in("uid", shoppingCarts.stream().map(m -> m.getOffsetProductUid()).collect(Collectors.toList()));
        List<UserInfo> userInfoList = userInfoService.selectList(userInfoWrapper);


        List<ShoppingCartExt> shoppingCartList = shoppingCarts.stream().map(ShoppingCartExt::new).collect(Collectors.toList());

        shoppingCartList.stream().forEach(item->{

            Integer offsetProductUid = item.getOffsetProductUid();
            userInfoList.stream().filter(f->f.getUid().intValue() == offsetProductUid.intValue()).findFirst().ifPresent(p->{
                item.setTradeStall(p.getTradeStall());
                item.setStoreName(p.getStoreName());
                item.setMobile(p.getMobile());
                item.setWeixin(p.getWeixin());
                item.setGate(p.getUid());
                item.setRandom(p.getRandom());
            });
        });

        retMap.put("shoppingCartList",shoppingCartList);
        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 更新加购
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/shop_update")
    public JsonResult shop_update(HttpServletRequest request, HttpServletResponse response){

        Integer uID = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        Map<String,Object> retMap;

        if( null == uID){
            retMap = new HashMap<>();
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        retMap = new HashMap<>();

        String offsetProductId = request.getParameter("productId");


        if(null == offerProductService.selectById(offsetProductId)) {
            retMap.put("msg", "无效产品");
            return JsonResult.buildError(retMap);
        }

        EntityWrapper<ShoppingCart> shoppingCartEntityWrapper = new EntityWrapper();
        shoppingCartEntityWrapper.eq("offset_product_id",offsetProductId);
        shoppingCartEntityWrapper.eq("uid",uID);
        shoppingCartEntityWrapper.eq("store",0);
        ShoppingCart shoppingCart = shopService.selectOne(shoppingCartEntityWrapper);

        if(null == shoppingCart) {

            retMap.put("msg", "产品不在购物车内");
            return JsonResult.buildError(retMap);

        }

        String num = request.getParameter("num");

        if(StringUtils.isNotBlank(num)){
            shoppingCart.setNum(Integer.parseInt(num));
        }

        String status = request.getParameter("status");

        if(StringUtils.isNotBlank(status)){ //更新已拿
            shoppingCart.setStatus(Integer.parseInt(status));
        }

        shoppingCart.setUpdateTime(new Date());
        shopService.updateById(shoppingCart);

        return JsonResult.buildSuccess(retMap);
    }


    /**
     * 删除加购车
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/shop_delete")
    public JsonResult shop_delete(HttpServletRequest request, HttpServletResponse response){

        Integer uID = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

        Map<String,Object> retMap;

        if( null == uID){
            retMap = new HashMap<>();
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        retMap = new HashMap<>();

        String offsetProductId = request.getParameter("productId");

        if(!offsetProductId.trim().contains(",")){
            if(null == offerProductService.selectById(offsetProductId)) {
                retMap.put("msg", "无效的产品");
                return JsonResult.buildError(retMap);
            }


            EntityWrapper<ShoppingCart> shoppingCartEntityWrapper = new EntityWrapper();
            shoppingCartEntityWrapper.eq("offset_product_id",offsetProductId);
            shoppingCartEntityWrapper.eq("uid",uID);
            shoppingCartEntityWrapper.eq("store",0);
            ShoppingCart shoppingCart = shopService.selectOne(shoppingCartEntityWrapper);

            if(null == shoppingCart) {

                retMap.put("msg", "产品不在购物车");
                return JsonResult.buildError(retMap);

            }

            shopService.deleteById(shoppingCart.getId());
        }else{


            List<String> productIds = Arrays.asList(offsetProductId.trim().split(",")).stream().filter(f->{

                try {
                    Integer.parseInt(f);
                    return true;
                }catch (Exception e){

                }
                return false;
            }).collect(Collectors.toList());

            EntityWrapper<ShoppingCart> shoppingCartEntityWrapper = new EntityWrapper();
            shoppingCartEntityWrapper.in("offset_product_id",productIds);
            shoppingCartEntityWrapper.eq("uid",uID);
            shoppingCartEntityWrapper.eq("store",0);
            List<ShoppingCart> shoppingCarts = shopService.selectList(shoppingCartEntityWrapper);

            List<Integer> deleteList = shoppingCarts.stream().map(m -> m.getId()).collect(Collectors.toList());

            shopService.deleteBatchIds(deleteList);
        }

        return JsonResult.buildSuccess(retMap);
    }
}
